﻿using FastServer.SwaggerDocument;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FastServer
{

    /// <summary>
    /// 规范化接口服务拓展类
    /// </summary>
    [AssemblyScanIgnore]
    public static class SwaggerServiceCollectionExtension
    {
        /// <summary>
        /// 添加规范化文档服务
        /// </summary>
        /// <param name="mvcBuilder">Mvc 构建器</param>
        /// <param name="configure">自定义配置</param>
        /// <returns>服务集合</returns>
        public static IMvcBuilder AddSwaggerDocument(this IMvcBuilder mvcBuilder, Action<SwaggerGenOptions>? configure = default)
        {
            mvcBuilder.Services.AddSwaggerDocument(configure);

            return mvcBuilder;
        }

        /// <summary>
        /// 添加规范化文档服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configure">自定义配置</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddSwaggerDocument(this IServiceCollection services, Action<SwaggerGenOptions>? configure = default)
        {
            // 判断是否启用规范化文档
            if (App.Settings?.InjectSwaggerDocument != true) return services;

            // 添加配置
            services.AddConfigurableOptions<SwaggerDocumentSettingsOptions>();

#if !NET5_0
            services.AddEndpointsApiExplorer();
#endif

            // 添加Swagger生成器服务
            services.AddSwaggerGen(options => SwaggerDocumentBuilder.BuildGen(options, configure));

            // 添加 MiniProfiler 服务
            AddMiniProfiler(services);

            return services;
        }

        /// <summary>
        /// 添加 MiniProfiler 配置
        /// </summary>
        /// <param name="services"></param>
        private static void AddMiniProfiler(IServiceCollection services)
        {
            // 注册MiniProfiler 组件
            if (App.Settings?.InjectMiniProfiler != true) return;

            services.AddMiniProfiler(options =>
            {
                // 减少非 Swagger 页面请求监听问题
                options.ShouldProfile = (req) =>
                {
                    if (!req.Headers.ContainsKey("request-from")) return false;
                    return true;
                };

                options.RouteBasePath = "/index-mini-profiler";
                options.EnableMvcFilterProfiling = false;
                options.EnableMvcViewProfiling = false;
            });
                //.AddRelationalDiagnosticListener();
        }
    }
}
